package com.example.covid19.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.example.covid19.common.lang.Result;
import okhttp3.*;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("/GQc")
public class TestApi {

    @RequestMapping("/createQr")
    public Result createQr(@RequestParam("text") String text) {
        System.out.println(text);
        String res = createQr(text, false);
        if (res == null) {
            System.out.println(-1);
        }
        return Result.success(200, "ok", JSONUtil.parseObj(res));
    }

    public static String createQr(String target, boolean isUrlCode) {
        String url = "https://cli.im/Apis/QrCode/saveStatic";
        try {
            RequestBody body;
            if (isUrlCode) {
                body = createUrl(target);
            } else {
                body = createText(target);
            }
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url).post(body).build();
            Call call = client.newCall(request);
            Response response = call.execute();
            if (response.code() == 200) {
                return Objects.requireNonNull(response.body()).string();
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static FormBody createUrl(String target) {
        return new FormBody.Builder()
                .add("info", target)
                .add("content", target)
                .add("level", "H")
                .add("size", "500")
                .add("fgcolor", "#000000")
                .add("bggcolor", "#FFFFFF")
                .add("transparent", "false")
                .add("type", "url")
                .add("codetype", "qr")
                .add("rawinfo", target)
                .build();
    }

    public static FormBody createText(String target) {
        return new FormBody.Builder()
                .add("info", target)
                .add("content", target)
                .add("level", "H")
                .add("size", "500")
                .add("fgcolor", "#000000")
                .add("bggcolor", "#FFFFFF")
                .add("transparent", "false")
                .add("type", "text")
                .add("codetype", "qr")
                .build();
    }
}
